package com.example.ucs.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.example.ucs.resp.AuthResp;
import com.example.ucs.restful.ResultCodeEnum;
import com.example.ucs.restful.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class GlobalApiInterceptor implements HandlerInterceptor {


    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("Interceptor preHandle:请求前调用");
        String accessToken = request.getHeader("accessToken");
        if (StrUtil.isBlank(accessToken)){
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(new ResultVO(ResultCodeEnum.TOKEN_NULL.getCode(),ResultCodeEnum.TOKEN_NULL.getMsg())));
            writer.flush();
            //返回 false 则请求中断
            return false;
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("accessToken", accessToken);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> resEntity = restTemplate.exchange("http://localhost:8033/authAccess",
                HttpMethod.GET, requestEntity, String.class);

        ResultVO resultVO = JSON.parseObject(resEntity.getBody(), ResultVO.class);
        if (resultVO.getCode() == 0) {
            AuthResp authResp = JSON.parseObject(resultVO.getData().toString(), AuthResp.class);
            log.info("authResp:{}",authResp);
            return true;

        } else {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(resultVO));
            writer.flush();
            //返回 false 则请求中断
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("Interceptor postHandle:请求后调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("Interceptor afterCompletion:请求调用完成后回调方法，即在视图渲染完成后回调");
    }
}
